package com.bearcloud.controller;

import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
public class UploadController {

    // 文件根目录
    private static final String UPLOAD_DIR = "files";

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        // file 校验
        if (file.isEmpty()) {
            return "文件为空";
        }

        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        String path = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() +
                "/" + UPLOAD_DIR + "/";
        // path += username;
        File filePath = new File(path);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }

        try {
            file.transferTo(new File(filePath, file.getOriginalFilename()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return "File saved.";
    }
}
